import React,{useEffect, useRef, useState} from "react";
import {Tabs,Form,Select,Input,Tooltip,Button,Tag,message,notification,Modal} from 'antd'
import LlxForm from 'components/LlxForm/index'
import classNames from "classnames";
import { connect } from 'react-redux'
import {setPageData,addHistoryRouter,setDictionaries,checkPublishData} from 'redux/action'
import LlxTable from 'components/LlxTable'
import {getAllPool,getSongPool,pushPool,delPoolData} from 'api/index'
import PushAudio from 'components/LlxPushData/audio'
import PreviewAudio from 'components/LlxPreview/audio'
const {TabPane} = Tabs
const {Search} = Input
const ClassifyData = (props) => {
  const {isModalVisible, setIsModalVisible,dataId,form,options} = props

  const loading = useRef(false)

  const [formItems] = Form.useForm()
  
  // 新增表单
const newWordItem = [
  {label: '电台分类',name: 'poolId' , span: 20, rules:[
    {
      required: true,
      message: '请选择电台分类'
    },
  ],render: () => {
    return <Select
    allowClear
    optionFilterProp="poolName"
    showSearch
    fieldNames={{value:'id',label:'poolName'}}
    placeholder={'请选择电台分类'}
    options= {options}
  >
  </Select>
  } }
]

  const handleOk = () => {
    if(loading.current) return
    
    loading.current=true
    formItems.validateFields().then(async()=>{

      await pushPool({
        dataId: dataId,
        levelId: form.getFieldValue().levelId || 106,
        poolId: formItems.getFieldValue().poolId,
        type: 'SONG'
      })
    
      notification.success({
        message: '添加成功',
        duration:1
      });

      form.resetFields()
      setIsModalVisible(false);

      props.getNewList()
    }).catch(err=>{
      console.log(err);
    }).finally(()=>{
      loading.current=false
    })
  };

  const handleCancel = () => {
    formItems.resetFields()
    setIsModalVisible(false);
  };

  return   <Modal width={700} title="选择电台分类" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <LlxForm form={formItems} labelCol={8} formItem={newWordItem} />
   </Modal>
}


function AudioPool(props) {

const {dictionaries} = props
const userName = props.userInfo.userName
const [form] = Form.useForm()
const [loading,setLoading] = useState(false)
const [total,setTotal] = useState(false)
const [tabIndex,setTabIndex] = useState('1')
const [isModalVisiblePushAudio,setIsModalVisiblePushAudio] = useState(false)

const [isModalVisiblePreivew,setIsModalVisiblePreivew] = useState(false)
const [isModalVisibleClassify,setIsModalVisibleClassify] = useState(false)
const [dataId,setDataId] = useState([])
const [Items,setItems] = useState({})
//分页数据
const [pagination,setPagination] = useState({
  current:1,
  pageSize:20
})
//初始表格数据
const [dataSource,setDataSource] = useState([])

const columns = [
  {title: '名称',fixed:'left', dataIndex: 'songName',width:250, key: 'songName', align: 'center',render: (text, record) => {
    return <div className="operate_link_group text-nowrap text-link" onClick={()=>goInfo(record.id,'SONG')}>
      {text}
   </div>
 }},
 {title: '素材状态', dataIndex: 'upperLowerName',width:100, key: 'upperLowerName', align: 'center',render: (text, record) => {
  return <div className="operate_link_group text-nowrap">
    {
      text==='已上架'?<Tag  color="success">{text}</Tag>:<Tag  color="red">{text}</Tag>
    }
 </div>}},
  {title: '适合年纪', dataIndex: 'ageName',width:100, key: 'ageName', align: 'center'},
  {title: '发行方', dataIndex: 'publisher',width:150, key: 'publisher', align: 'center'},
  {title: '主题', dataIndex: 'themes',width:180, key: 'themes', align: 'center', render: (text, record) => {
    return <div className="operate_link_group text-nowrap">
     {record.themes?.map((i,j)=>{
       return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.themeName).join(' ')}>
        {
          j<3?<Tag key={i.id} color="lime">{i.themeName}</Tag>:''
        }
         </Tooltip>
     })}
   </div>}
  },
  {title: '系列', dataIndex: 'serialName',width:150, key: 'serialName', align: 'center'},
  {title: '类型', dataIndex: 'songCategoryName',width:150, key: 'songCategoryName', align: 'center'},
  {title: '标签', dataIndex: 'labels', key: 'labels',width:180, align: 'center', render: (text, record) => {
   return <div className="operate_link_group text-nowrap">
    {record.labels?.map((i,j)=>{
      return   <Tooltip key={i.id} placement="top" title={text.map(i=>i.labelName).join(' ')}>
       {
         j<3?<Tag key={i.id} color="green">{i.labelName}</Tag>:''
       }
        </Tooltip>
    })}
  </div>
}},
  {title: '创建人',width:120, dataIndex: 'createBy', key: 'createBy', align: 'center',render: (text, record) => {
    return <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
      {text}
   </div>
 }},
  {title: '更新人',width:120, dataIndex: 'updateBy', key: 'updateBy', align: 'center',render: (text, record) => {
    return  <div className={classNames(userName===text?'operate_link_group text-nowrap text-color-red':"operate_link_group text-nowrap")}>
    {text}
 </div>
 }},
  {title: '更新时间', dataIndex: 'updateTime', key: 'updateTime', align: 'center',width:180},
  {title: '操作',fixed:'right', dataIndex: 'operate', key: 'operate', align: 'center',width:100,render:(text,row)=>{
    return  <div className="text-link" onClick={()=>previewAudio(row)}>
     预览
   </div>
  }}
]
// 分类数据
const [classificationList,setClassificationList] = useState([])

// 表单数据
const formItem = [
  {label: '级别', name: 'levelId', span: 5,render: () => {
    return <Select
    defaultValue={106}
    optionFilterProp="dictValue"
    showSearch
    fieldNames={{value:'id',label:'dictValue'}}
    placeholder={'请选择级别'}
    options={dictionaries.Level}
  >
  </Select>
}},
{label: '素材状态', name: 'upperLower', span: 5,render: () => {
  return <Select
  allowClear
  optionFilterProp="dictValue"
  showSearch
  fieldNames={{value:'id',label:'dictValue'}}
  placeholder={'请选择状态'}
  options={[{dictValue:'已上架',id:1010},{dictValue:'已下架',id:1000}]}
>
</Select>
}},
{label: '创建人', name: 'createBy',  span: 5 ,render: () => {
  return <Select
  allowClear
  optionFilterProp="userName"
  showSearch
  fieldNames={{value:'userName',label:'userName'}}
  placeholder={'请选择创建人'}
  options={dictionaries.UserSpecies}
>
</Select>
}},
{label: '', name: 'name' , span: 5,render: () => {
    return  <Search placeholder="请输入关键词搜索" onSearch={getNewList} enterButton />
} }
]
//选择数据
const [selectedRowKeys,setselectedRowKeys] = useState([])
const rowSelection  = useRef({
  selectedRowKeys: selectedRowKeys,
  onChange: value => {
  setselectedRowKeys(value)
  rowSelection.current.selectedRowKeys = value
  }
})

// 初始化
//1缓存页面数据 缓存表单数据
useEffect(()=>{
  form.setFieldsValue(props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.form)
  setPagination(props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination||{
    current:1,
    pageSize:20
  })
  },[]) // eslint-disable-line react-hooks/exhaustive-deps

// 1.切换tab
const callback = (key)  => {
    setTabIndex(key)
    setPagination({
      current:1,
      pageSize:20
    })
}
// 1.1
  useEffect(()=>{
    getNewList()
  },[tabIndex]) // eslint-disable-line react-hooks/exhaustive-deps

  // 2.获取数据
  const getNewList = async(value) => {
    setIsModalVisiblePushAudio(false)
   // 清空选中状态
   setselectedRowKeys(()=>[])
   rowSelection.current.selectedRowKeys=[]

   setLoading(true)

  // 获取tab分类数据
  const res = await getAllPool()
  setClassificationList([{poolName:'全部',id:'1'},...res.result[1].configList])

  const params = {
    currPage:value&&value.pageSize?value.current:pagination.current,
    pageSize:value&&value.pageSize?value.pageSize:pagination.pageSize,
    createBy:form.getFieldValue().createBy,
    levelId:form.getFieldValue().levelId || 106,
    bookName:form.getFieldValue().bookName,
    upperLower:form.getFieldValue().upperLower,
    poolId:tabIndex==='1'?'':tabIndex
  }

  if(props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination&&(props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination.current!==1||props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination.pageSize!==10)&&pagination.current===1&&pagination.pageSize===10){
    params.currPage=props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination.current
    params.pageSize=props.tabList.filter(i=>i.url==='areaPush/areaPushAudioLibrary')[0]?.data?.pagination.pageSize
  }

  const data = {
    pagination: value&&value.pageSize?value:pagination,
    form:form.getFieldValue()
 }
   props.setPageDataFn('areaPush/areaPushAudioLibrary',data) 
  const res1 = await getSongPool(params)

  const data1 = res1.result.records

  data1.forEach((i,j)=>{
    i.sort=j+1
  })
  setDataSource(()=>data1)

  setTotal(res1.result.total)

  setLoading(false)

  }
//  3.去详情
const goInfo = (value) => {
  props.checkPublishDataBtn()
  props.history.push('/view/audio/audioInfo?id=' + value.id)
  props.addRouter({
    menuName:'音频详情',url:'audio/audioInfo?id=' + value.id 
  })
}
// 4.拉音频数据
const pushAudioPool = () => {
  setIsModalVisiblePushAudio(true)
}
// 5.移除
const delPoolDatas =async () =>{
  const data = dataSource.filter((i)=>selectedRowKeys.includes(i.sort)).map(i=>i.pushPoolId)
  for (let i = 0; i < data.length; i++) {
    await delPoolData(data[i])
  }
    message.success('移除成功')
   getNewList()
 

}
// 6.获取新增数据
const returnId = (value) => {

  setDataId(value)


  setIsModalVisibleClassify(true)
}
// 预览音频
const previewAudio = (i) => {
  setItems({
    audioUrl:i.audioUrl,
    srtUrl:i.songSrt
  })
  setIsModalVisiblePreivew(true)
}


     return  <div  className="app-content animate__animated animate__fadeIn overflow">

    <LlxForm form={form} formItem={formItem}/>

    <div className="operate-btn">
     <div>
           <Button  onClick={pushAudioPool} type='primary' className='animate__animated animate__fadeInLeft'>新增</Button>
           <Button danger onClick={delPoolDatas} disabled={!selectedRowKeys.length} type='primary' className='animate__animated animate__fadeInLeft'>移除推送池</Button>
       </div>
    </div>

    <Tabs  activeKey={tabIndex} onChange={callback} className="app-content animate__animated animate__fadeIn">
      {
        classificationList.map((i,j)=>{
          return  <TabPane tab={i.poolName} key={i.id}>
          <LlxTable
          loading={loading} 
          pagination={pagination}
          setPagination={setPagination}
          selectedRowShow={true}
          keyName={'sort'}
          rowSelection={rowSelection.current}
          height={365}
          total={total}
          getNewList={getNewList}
          columns={columns}
          dataSource={dataSource}/>
       </TabPane>
        })
      }
    </Tabs>
    <PreviewAudio prevewAudio={Items} isModalVisible={isModalVisiblePreivew} setIsModalVisible={setIsModalVisiblePreivew}></PreviewAudio>

    <ClassifyData getNewList={getNewList} form={form} dataId={dataId} options={classificationList.filter(i=>i.poolName!=='全部')} isModalVisible={isModalVisibleClassify} setIsModalVisible={setIsModalVisibleClassify}></ClassifyData>

    <PushAudio returnId={returnId} title={'电台新增音频'} multipleType={true} userName={props.userInfo.user.userName} dictionaries={props.dictionaries} isModalVisible={isModalVisiblePushAudio} setIsModalVisible={setIsModalVisiblePushAudio}></PushAudio>
     </div>
}


// 映射方法
const mapDispatchToProps = (dispatch) => {
  return {
    checkPublishDataBtn: () => dispatch(checkPublishData()),
    addRouter: (route) => dispatch(addHistoryRouter(route)),
    setPageDataFn: (url,data) => dispatch(setPageData(url,data)),
    setDictionaries: (url,data) => dispatch(setDictionaries(url,data))
  }
}

export default connect((state)=>{
  return {tabList:state.tabList,examineStatus:state.examineStatus,userInfo:state.userInfo,dictionaries:state.dictionaries}
},mapDispatchToProps)(AudioPool)
